package cn.kgc.service;


import cn.kgc.common.CrowdFundingUtils;
import cn.kgc.mapper.UserMapper;
import cn.kgc.pojo.User;
import cn.kgc.pojo.UserExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("loginService")
public class LoginServiceImpl implements LoginService {


    @Resource
    UserMapper userMapper;
//    @Override
//    public User login(String username, String userpassword) {
//            User user=null;
//            user=loginMapper.login(username);
//            if(user!=null){
//            if(!user.getUserpassword().equals(userpassword)){
//                user=null;
//            }
//            }
//        return user;
//    }

    @Override
    public User login(String username, String userpassword) {
        //根据loginacct查询admin
        //判断是否为空
        //如果不为空给密码加密
        //和数据库的密码比较
        //如果一样,登录成功
        User user = null;
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        UserExample.Criteria criteria1 = example.createCriteria();
        criteria1.andEmailEqualTo(username);
        UserExample.Criteria criteria2 = example.createCriteria();
        criteria2.andPhoneEqualTo(username);
        example.or(criteria1);
        example.or(criteria2);

        List<User> list = userMapper.selectByExample(example);

        if (CrowdFundingUtils.collectionEffective(list)) {
            user = list.get(0);
            String md5 = CrowdFundingUtils.md5(userpassword);
            if (md5.equals(user.getUserpassword())) {
                //成功
                return user;
            } else {
                //失败
                user = null;
            }
        }
        return user;
    }

    @Override
    public void AddUser(User user) {
        String userPswd = user.getUserpassword();
        userPswd = CrowdFundingUtils.md5(userPswd);
        user.setUserpassword(userPswd);
        userMapper.insert(user);
    }

    @Override
    public User selectUserById(String phone) {
        return userMapper.selectByPrimaryKey(phone);
    }

//    @Override
//    public void updatePassword(User user) {
//        String userPswd = user.getUserpassword();
//        userPswd = CrowdFundingUtils.md5(userPswd);
//        user.setUserpassword(userPswd);
//        userMapper.updateByPrimaryKeySelective(user);
//    }


}
